/**
 * Copyright (C), 2020, JieYi Software System Co., Ltd.
 * All rights reserved.
 * FileName:       MdmsSshserverService.java
 *
 * @Description:
 * @author: feiwe
 * Modification History:
 * Date         Author        Version        Discription
 * -------------------------------------------------------
 * 2020/12/3      feiwe                         add
 */


package com.fengwei.service;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.fengwei.config.CommonProperty;
import com.fengwei.dao.MdmsSshserverMapper;
import com.fengwei.dao.MdmsSshserverUserMapper;
import com.fengwei.dao.MdmsUserSshserverMapper;
import com.fengwei.form.MdmsSshserver;
import com.fengwei.form.MdmsSshserverUser;
import com.fengwei.form.MdmsUser;
import com.fengwei.form.MdmsUserLog;
import com.fengwei.form.MdmsUserSshserver;
import com.fengwei.requestdata.sshserver.MdmsSshserverAddData;
import com.fengwei.requestdata.sshserver.MdmsSshserverAddServerUserData;
import com.fengwei.requestdata.sshserver.MdmsSshserverDelData;
import com.fengwei.requestdata.sshserver.MdmsSshserverDelServerUserData;
import com.fengwei.requestdata.sshserver.MdmsSshserverEditData;
import com.fengwei.requestdata.sshserver.MdmsSshserverGetServerUsersByServerIdData;
import com.fengwei.requestdata.sshserver.MdmsSshserverPagingListData;
import com.fengwei.requestdata.sshserver.MdmsSshserverQueryMyServersData;
import com.fengwei.requestdata.user.MdmsUserDelSignUserData;
import com.fengwei.requestdata.user.MdmsUserSignUserData;
import com.fengwei.util.HexStringUtil;
import com.fengwei.util.MdmsConsts;
import com.fengwei.util.PltResult;
import com.fengwei.util.SnowflakeIdWorker;
import com.fengwei.util.VerifyException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MdmsSshserverService {
    private final static Logger logger = LoggerFactory.getLogger(MdmsSshserverService.class);

    @Autowired
    private MdmsSshserverMapper mdmsSshserverMapper;

    @Autowired
    private MdmsSshserverUserMapper mdmsSshserverUserMapper;

    @Autowired
    private MdmsUserSshserverMapper mdmsUserSshserverMapper;

    @Autowired
    private CommonProperty commonProperty;

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    public Map<String, Object> pagingList(MdmsSshserverPagingListData mdmsSshserverPagingListData) {
        Map<String, Object> mapPagingList = new HashMap();

        PageHelper.startPage(mdmsSshserverPagingListData.getPage(), mdmsSshserverPagingListData.getLimit());
        PageHelper.orderBy("id desc");
        Page<MdmsUserLog> list = mdmsSshserverMapper.selectByPage(mapPagingList);

        Map<String, Object> mapReturn = new HashMap<>(8);
        mapReturn.put("total", list.getTotal());
        mapReturn.put("limit", mdmsSshserverPagingListData.getLimit());
        mapReturn.put("page", mdmsSshserverPagingListData.getPage());
        mapReturn.put("list", list.getResult());
        return mapReturn;
    }

    public Map<String, Object> add(MdmsSshserverAddData mdmsSshserverAddData) {
        Map<String, Object> returnData = new HashMap<>();
        MdmsSshserver mdmsSshserverInsert = new MdmsSshserver();
        mdmsSshserverInsert.setId(snowflakeIdWorker.nextId());
        mdmsSshserverInsert.setServerName(mdmsSshserverAddData.getServerName());
        mdmsSshserverInsert.setServerHost(mdmsSshserverAddData.getServerHost());
        mdmsSshserverInsert.setServerPort(Integer.parseInt(mdmsSshserverAddData.getServerPort()));
        mdmsSshserverMapper.insert(mdmsSshserverInsert);

        return returnData;
    }

    public Map<String, Object> edit(MdmsSshserverEditData mdmsSshserverEditData) {
        Map<String, Object> returnData = new HashMap<>();
        Map mapSelectByPrimaryKey = new HashMap();
        mapSelectByPrimaryKey.put("id", mdmsSshserverEditData.getId());
        MdmsSshserver mdmsSshserver = mdmsSshserverMapper.selectByPrimaryKey(mapSelectByPrimaryKey);
        if (null == mdmsSshserver) {
            // 服务器不存在
            throw new VerifyException(PltResult.RESULT_CF320);
        } else {
            MdmsSshserver mdmsSshserverUpdate = new MdmsSshserver();
            mdmsSshserverUpdate.setId(mdmsSshserver.getId());
            mdmsSshserverUpdate.setServerName(mdmsSshserverEditData.getServerName());
            mdmsSshserverUpdate.setServerHost(mdmsSshserverEditData.getServerHost());
            mdmsSshserverUpdate.setServerPort(Integer.parseInt(mdmsSshserverEditData.getServerPort()));
            mdmsSshserverMapper.update(mdmsSshserverUpdate);
        }

        return returnData;
    }

    public Map<String, Object> del(MdmsSshserverDelData mdmsSshserverDelData) {
        Map<String, Object> returnData = new HashMap<>();
        Map mapSelectByPrimaryKey = new HashMap();
        mapSelectByPrimaryKey.put("id", mdmsSshserverDelData.getId());
        MdmsSshserver mdmsSshserver = mdmsSshserverMapper.selectByPrimaryKey(mapSelectByPrimaryKey);
        if (null == mdmsSshserver) {
            // 服务器不存在
            throw new VerifyException(PltResult.RESULT_CF320);
        } else {
            MdmsSshserver mdmsSshserverDel = new MdmsSshserver();
            mdmsSshserverDel.setId(mdmsSshserver.getId());
            mdmsSshserverMapper.delete(mdmsSshserverDel);
        }

        return returnData;
    }

    public Map<String, Object> getServerUsersByServerId(MdmsSshserverGetServerUsersByServerIdData mdmsSshserverGetServerUsersByServerIdData, MdmsUser mdmsUser, HttpServletRequest request) {
        Map<String, Object> returnData = new HashMap<>();
        Map mapGetServerUsersByServerId = new HashMap();
        mapGetServerUsersByServerId.put("serverId", mdmsSshserverGetServerUsersByServerIdData.getServerId());
        List<MdmsSshserverUser> serverUsers = mdmsSshserverUserMapper.selectAll(mapGetServerUsersByServerId);
        returnData.put("list", serverUsers);
        return returnData;
    }

    public Map<String, Object> addServerUser(MdmsSshserverAddServerUserData mdmsSshserverAddServerUserData, MdmsUser mdmsUser, HttpServletRequest request) {
        Map<String, Object> returnData = new HashMap<>();
        MdmsSshserverUser mdmsSshserverUser = new MdmsSshserverUser();
        mdmsSshserverUser.setId(snowflakeIdWorker.nextId());
        mdmsSshserverUser.setServerId(mdmsSshserverAddServerUserData.getServerId());
        mdmsSshserverUser.setServerUser(mdmsSshserverAddServerUserData.getServerUser());
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, HexStringUtil.hexStringToBytes(commonProperty.getSshserverAesKey()));
        String databasePasswordHex = aes.encryptHex(mdmsSshserverAddServerUserData.getServerPassword());
        mdmsSshserverUser.setServerPassword(databasePasswordHex);
        mdmsSshserverUserMapper.insert(mdmsSshserverUser);
        return returnData;
    }

    public Map<String, Object> delServerUser(MdmsSshserverDelServerUserData mdmsSshserverDelServerUserData, MdmsUser mdmsUser, HttpServletRequest request) {
        Map<String, Object> returnData = new HashMap<>();
        Map mapSelectByPrimaryKey = new HashMap();
        mapSelectByPrimaryKey.put("id", mdmsSshserverDelServerUserData.getId());
        MdmsSshserverUser mdmsSshserverUser = mdmsSshserverUserMapper.selectByPrimaryKey(mapSelectByPrimaryKey);
        if (null == mdmsSshserverUser) {
            // 数据库不存在
            throw new VerifyException(PltResult.RESULT_CF320);
        } else {
            MdmsSshserverUser mdmsSshserverUserDel = new MdmsSshserverUser();
            mdmsSshserverUserDel.setId(mdmsSshserverUser.getId());
            mdmsSshserverUserMapper.delete(mdmsSshserverUserDel);
        }

        return returnData;
    }

    public Map<String, Object> signUser(MdmsUserSignUserData mdmsUserSignUserData, MdmsUser mdmsUser, HttpServletRequest request) {
        Map<String, Object> returnData = new HashMap<>();
        MdmsUserSshserver mdmsUserSshserver = new MdmsUserSshserver();
        mdmsUserSshserver.setId(snowflakeIdWorker.nextId());
        mdmsUserSshserver.setUserId(mdmsUserSignUserData.getUserId());
        mdmsUserSshserver.setServerId(mdmsUserSignUserData.getServerId());
        mdmsUserSshserver.setServerUserId(mdmsUserSignUserData.getServerUserId());
        mdmsUserSshserverMapper.insert(mdmsUserSshserver);
        return returnData;
    }

    public Map<String, Object> delSignUser(MdmsUserDelSignUserData mdmsUserDelSignUserData, MdmsUser mdmsUser, HttpServletRequest request) {
        Map<String, Object> returnData = new HashMap<>();
        Map mapSelectByUKey = new HashMap();
        mapSelectByUKey.put("userId", mdmsUserDelSignUserData.getUserId());
        mapSelectByUKey.put("serverUserId", mdmsUserDelSignUserData.getServerUserId());
        MdmsUserSshserver mdmsUserSshserver = mdmsUserSshserverMapper.selectByUKey(mapSelectByUKey);
        if (null == mdmsUserSshserver) {
            throw new VerifyException(PltResult.RESULT_CF319);
        }
        MdmsUserSshserver mdmsUserSshserverDelete = new MdmsUserSshserver();
        mdmsUserSshserverDelete.setId(mdmsUserSshserver.getId());
        mdmsUserSshserverMapper.delete(mdmsUserSshserverDelete);
        return returnData;
    }

    public Map<String, Object> queryMyServers(MdmsSshserverQueryMyServersData mdmsSshserverQueryMyServersData, MdmsUser mdmsUser, HttpServletRequest request) {
        Map<String, Object> returnData = new HashMap<>();
        Map mapQueryMyServers = new HashMap();
        if (!MdmsConsts.USER_TYPE_99.equals(mdmsUser.getUserType())) {
            mapQueryMyServers.put("userId", mdmsUser.getId());
        }

        HttpSession session = request.getSession();

        //随机生成密钥，用来保护user的id的，然后放在session里面
        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        session.setAttribute("serverUserKey" + mdmsUser.getId(), HexStringUtil.bytesToHexString(key));

        List serverInfo = new ArrayList();
        List<MdmsSshserver> myServers = mdmsSshserverMapper.queryMyServers(mapQueryMyServers);
        List<MdmsSshserverUser> myServerUsers = mdmsSshserverUserMapper.queryMyServerUsers(mapQueryMyServers);
        for (MdmsSshserver ms : myServers) {
            Map mapServer = new HashMap();
            mapServer.put("id", ms.getId() + "");
            mapServer.put("name", ms.getServerName() + "");
            mapServer.put("type", "server");
            mapServer.put("iconCls", "icon-diy-server1");
            List<Map<String, String>> serverUserList = new ArrayList();
            for (MdmsSshserverUser msu : myServerUsers) {
                if (ms.getId().longValue() == msu.getServerId().longValue()) {
                    Map mapServerUser = new HashMap();
                    mapServerUser.put("id", aes.encryptHex(msu.getId() + ""));
                    mapServerUser.put("name", msu.getServerUser() + "");
                    mapServerUser.put("type", "user");
                    mapServerUser.put("iconCls", "icon-diy-user1");
                    serverUserList.add(mapServerUser);
                } else {
                    //nothing to do
                }
            }
            mapServer.put("children", serverUserList);
            if (serverUserList.size() > 0) {
                serverInfo.add(mapServer);
            }
        }
        returnData.put("serverInfo", serverInfo);

        return returnData;
    }


}
